<template xmlns = "">
  <div v-if = "isshow">users</div>
  <div v-else class = "user">
    <self-breadcrumb :bread-arr = "userBread"></self-breadcrumb>
    <el-card>
      <div slot = "header" class = "clearfix card_box">
        <!--
            el中的大部分元素都设置为块级元素，我们需要使用el的布局容器 布局容器将一行分为24分栏
            gutter是栅格间隔  单位为像素
            span是栅格的所占的列数 最多只有24列
            其他的建议去el官网查看
        -->
        <el-row :gutter = "10">
          <el-col :span = "6">
            <!-- el-input可以嵌套其他组件比如这里的按钮组件 -->
            <!-- clearable是el-input自带的属性，可以用于清空该输入框，并且有一个对应的事件clear事件 点击清除键后触发 -->
            <el-input v-model = "params.query" placeholder = "姓名搜索" clearable @clear = "clearForm">
              <el-button slot = "append" icon = "el-icon-search" @click = "queryList"></el-button>
            </el-input>
          </el-col>
          <el-col :span = "6">
            <el-button type = "primary" @click = "dialogFormVisible =true">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data = "userlist" border style = "width: 100%">
        <el-table-column
          type = "index"
          label = "#">
        </el-table-column>
        <el-table-column
          prop = "username"
          label = "姓名">
        </el-table-column>
        <el-table-column
          prop = "email"
          label = "邮箱">
        </el-table-column>
        <el-table-column
          prop = "mobile"
          label = "电话">
        </el-table-column>
        <el-table-column
          prop = "role_name"
          label = "角色">
        </el-table-column>
        <el-table-column
          prop = "mg_state"
          label = "状态">
          <!--
              这是作用域插槽，是el组件源码设计的作用域插槽，el表格使用的数据是数组，所以每一行都遍历了数组
              所以每一行都有数组的数据，使用作用域插槽就可以使用子组件中的数据  所以我们这里使用作用域插槽
              使用scope接收数据 注意 一定要使用scope.row 才可以使用 如果直接输出scope并不能得到反而会报错
          -->
          <template slot-scope = "scope">
            <el-switch
              v-model = "scope.row.mg_state"
              active-color = "#409EFF"
              inactive-color = "#ff4949"
              @change = "mgStateChange(scope.row)">
            </el-switch>
            {{scope.row.mg_state}}
          </template>
        </el-table-column>
        <el-table-column
          label = "操作">
          <template slot-scope = "scope">
            <el-button size = "small" type = "primary" icon = "el-icon-edit"
                       @click = "editUserForm(scope.row)">
            </el-button>
            <el-button size = "small" type = "warning" icon = "el-icon-share" @click = "setRole(scope.row)"></el-button>
            <el-button size = "small"
                       type = "danger"
                       icon = "el-icon-delete"
                       @click = "deleteUsers(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--
        下面是分页组件，其中的方法和绑定值非常重要，主要是current-change事件，	currentPage 改变时会触发，
        并且这个事件会传入一个默认参数就是改变后的页面数，即使不传入参数也可以接收到。
        而且动态绑定的current-page可以使用.sync修饰符，这个修饰符作用就是当传入子组件的变量改变时，
        会自动触发事件，改变对应的父组件的值
        layout 是分页中组件的内容 slot插槽 sizes选择展示的信息条数 prev上一页按钮  pager总页数 next下一页按钮
        page-size是当前展示的信息条数默认为2 如果为2当前页面就只展示两条信息
        size-change 事件，当page-size发生变化时触发，可以用来重新设置当前的信息
        page-sizes值为一个数组，可以用于设置page-size的值，并且将值传递给size-change事件
        total 总条数，用于子组件计算
       -->
      <el-pagination
        background
        layout = "slot,sizes,prev, pager, next"
        :page-size = "params.pagesize"
        @current-change = "handleCurrentChange"
        @size-change = "handleSizeChange"
        :current-page.sync = "params.pagenum"
        @prev-click = "prevClick"
        @next-click = "nextClick"
        :page-sizes = "[1,2,3,4,5,10]"
        :total = "total">
        <!--
        el的分页组件是可以使用插槽的，但是需要在上面的layout属性中添加slot 但是这里的插槽不像el-column一样是作用域插槽 ，
        这里只是普通的插槽，将插槽中的东西放到组件中而已，注意 有一个插槽layout中就有几个slot，而且slot所在的地方就决定了
        插入的位置 ,比如上面的slot在首尾各有一个，所以插入的位置也是首尾各有一个，但是经过实践发现插入的内容
        是下面所有的，而且不能使用具名插槽，这个问题暂时无法解决
        -->
        <!--        <template><span>你好</span></template>-->
        <!--        <template><span>世界</span></template>-->
      </el-pagination>
    </el-card>
    <el-dialog title = "添加用户" :visible.sync = "dialogFormVisible" width = "40%">
      <el-form :model = "push_users" label-width = "80px" :rules = "user_rules" ref = "pushForm">
        <el-form-item label = "用户名" prop = "username">
          <el-input v-model = "push_users.username"></el-input>
        </el-form-item>
        <el-form-item label = "用户密码" prop = "password">
          <el-input v-model = "push_users.password" show-password></el-input>
        </el-form-item>
        <el-form-item label = "邮箱" prop = "email">
          <el-input v-model = "push_users.email" type = "email"></el-input>
        </el-form-item>
        <el-form-item label = "手机号" prop = "mobile">
          <el-input v-model = "push_users.mobile" type = "number"></el-input>
        </el-form-item>
      </el-form>
      <div slot = "footer" class = "dialog-footer">
        <el-button @click = "dialogFormVisible = false">取 消</el-button>
        <el-button type = "primary" @click = "pushUsers">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title = "提示"
      :visible.sync = "editVisible"
      width = "40%">
      <el-form :model = "editForm" label-width = "80px" :rules = "user_rules" ref = "edit_form">
        <el-form-item label = "用户名">
          <el-input v-model = "editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label = "邮箱" prop = "email">
          <el-input v-model = "editForm.email"></el-input>
        </el-form-item>
        <el-form-item label = "手机" prop = "mobile">
          <el-input v-model = "editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot = "footer" class = "dialog-footer">
        <el-button type = "warning" @click = "editVisible=false">取消</el-button>
        <el-button type = "primary" @click = "editUser">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title = "分配角色"
      :visible.sync = "setRoleDialogVisible"
      width = "50%">
      <el-form :model = "userinfo" label-width = "80px">
        <el-form-item label = "用户名">
          <el-input v-model = "userinfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label = "当前角色">
          <el-input v-model = "userinfo.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label = "角色">
          <el-select v-model = "setRoleMsg.rid">
            <el-option
              v-for = "item in roleList"
              :key = "item.id"
              :label = "item.roleName"
              :value = "item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot = "footer" class = "dialog-footer">
        <el-button @click = "setRoleDialogVisible = false">取 消</el-button>
        <el-button type = "primary" @click = "setRoleDefine">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SelfBreadcrumb from '../SelfBreadcrumb'

export default {
  name: 'User',
  components: { SelfBreadcrumb },
  data () {
    return {
      isshow: false,
      userlist: [],
      params: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      dialogFormVisible: false,
      editVisible: false,
      push_users: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      user_rules: {
        username: [
          // 用户名的验证规则，一个对象就是一个验证规则，其中包括了验证目的，验证信息，验证触发条件
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 12, message: '长度在4-10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在4-10之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ]
      },
      editForm: {},
      userBread: ['用户管理', '用户列表'],
      setRoleDialogVisible: false,
      userinfo: {},
      roleList: [],
      setRoleMsg: {}
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    getUserList () {
      this.$http.get('/users', {
        params: this.params
      }).then(ret => {
        const data = ret.data
        if (data.meta.status !== 200) {
          this.$message.error(data.meta.msg)
          this.isshow = true
        } else {
          this.userlist = data.data.users
          this.total = data.data.total
        }
      })
    },
    // 这里的这两个事件也需要在标签中绑定 @prev-click 或者 @next-click
    // 也有默认的参数，但是使用current-change完成跳转是完全够用的，所以这两个事件一般用来做其他的事情
    prevClick (val) {
      // console.log(val)
    },
    nextClick (val) {
      // console.log(val)
    },
    handleCurrentChange (val) {
      // 这个参数是默认的参数，是改变后的页面数
      console.log(val)
      this.getUserList()
    },
    handleSizeChange (newsize) {
      this.params.pagesize = newsize
      this.getUserList()
    },
    mgStateChange (state) {
      this.$http.put(`users/${state.id}/state/${state.mg_state}`).then(ret => {
        this.$process(ret, this.getUserList)
      })
    },
    queryList () {
      this.getUserList()
    },
    deleteUsers (del) {
      this.$http.delete(`users/${del.id}`).then(ret => {
        this.$process(ret, this.getUserList)
      })
    },
    clearForm () {
      this.getUserList()
    },
    pushUsers () {
      this.$refs.pushForm.validate((valid) => {
        if (!valid) return
        this.$http.post('users', this.push_users).then(ret => {
          this.$process(ret, this.getUserList)
        })
        this.$refs.pushForm.resetFields()
        this.dialogFormVisible = false
      })
    },
    editUserForm (user) {
      this.$http.get(`users/${user.id}`).then(ret => {
        this.$process(ret, this.getUserList)
        this.editForm = ret.data.data
        this.editVisible = true
        console.log(this.editForm)
      })
    },
    editUser () {
      this.$refs.edit_form.validate(valid => {
        if (!valid) return
        this.$http.put(`users/${this.editForm.id}`, this.editForm).then(ret => {
          this.$process(ret, this.getUserList)
          this.editVisible = false
        })
      })
    },
    async setRole (row) {
      this.userinfo = row
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      this.setRoleMsg.id = this.userinfo.id
      this.setRoleDialogVisible = true
    },
    async setRoleDefine () {
      const { data: res } = await this.$http.put(`users/${this.setRoleMsg.id}/role`, this.setRoleMsg)
      if (res.meta.status === 200) this.$message.success(res.meta.msg)
      else this.$message.error(res.meta.msg)
      this.getUserList()
      this.setRoleDialogVisible = false
    }
  },
  comments: {
    SelfBreadcrumb
  }
}
</script>

<style scoped>
  .user {
    background-color: #EAEDF1;
  }

  .el-card {
    margin: 20px 0px;
  }

  .el-pagination {
    margin-top: 20px;
  }

</style>
